import usersPagesTpl from '../views/pagination.art'
import page from '../databus/page'

const _setPageActive = (index) => {
  $('#users-pages #users-pages-list li:not(:first-child,:last-child').eq(index-1).addClass('active').siblings().removeClass('active');
}

// 分页
function pagination(data) {
  if(!data) return
  let currentPage = page.curPage
  let pageSize = page.pageSize
  const total = data.length
  let pageCount = Math.ceil(total / pageSize)
  const pageArray = new Array(pageCount)

  if(currentPage > 1 && currentPage > pageCount) {
    currentPage --
    page.setCurPage(currentPage)
  }

  // console.log(pageArray)
  // Array.from()

  $('#users-pages').html(usersPagesTpl({
    pageArray
  }))

  _setPageActive(currentPage)

  _bindEvent(pageCount)
}

function _bindEvent(pageCount) {
  
  $('#users-pages').off('click').on('click', '#users-pages-list li:not(:first-child,:last-child)', function () {
    // $(this).addClass('active').siblings().removeClass('active');
    const index = $(this).index()
    // _list(index)
    // currentPage = index
    _setPageActive(index)
    $('body').trigger('changeCurrentPage', index)
  })

  $('#users-pages').on('click', '#users-pages-list li:first-child', function () {
    let currentPage = page.curPage
    if(currentPage > 1) {
      currentPage--
    }
    // currentPage--
    // if(currentPage <= 1) {
    //   currentPage = 1
    // }
    _setPageActive(currentPage)
    // $('#users-pages-list li').eq(currentPage).addClass('active').siblings().removeClass('active');
    // _list(currentPage)
    
    $('body').trigger('changeCurrentPage', currentPage)
   
  })

  $('#users-pages').on('click', '#users-pages-list li:last-child', function () {
    let currentPage = page.curPage
    if(currentPage < pageCount) {
      currentPage++
    }
    // currentPage++
    // if(currentPage >= pageCount) {
    //   currentPage = pageCount
    // }
    _setPageActive(currentPage)
    // $('#users-pages-list li').eq(currentPage).addClass('active').siblings().removeClass('active');
    // _list(currentPage)
    $('body').trigger('changeCurrentPage', currentPage)
  })
}

export default pagination